package com.hk.webapp.utils.encryptions;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * (C) Copyright 2017-2019
 * All rights reserved.
 * <p>
 * 加密工具
 *
 * @author DreamerCK
 * @date 2017-12-06 22:55
 **/
public class EncryptUtil {

    private static final char PADDING_CHAR = '\0';
    private static String IV = "k21OIf0@#$9sjl@$";
    private static String encryptionKey = "d#@45$fd12E@#$12";

    public static String encrypt(String plainText) throws Exception {
        plainText = padding(plainText);
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
        SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes(StandardCharsets.UTF_8.displayName()), "AES");
        cipher.init(Cipher.ENCRYPT_MODE, key,new IvParameterSpec(IV.getBytes(StandardCharsets.UTF_8.displayName())));
        byte[] bytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8.displayName()));
        String s = new String(bytes, StandardCharsets.ISO_8859_1.displayName());
        return s;
    }

    public static String decrypt(String cipherText) throws Exception{
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
        SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes(StandardCharsets.UTF_8.displayName()), "AES");
        cipher.init(Cipher.DECRYPT_MODE, key,new IvParameterSpec(IV.getBytes(StandardCharsets.UTF_8.displayName())));
        byte[] decoded = cipherText.getBytes(StandardCharsets.ISO_8859_1.displayName());
        String s = new String(cipher.doFinal(decoded), StandardCharsets.UTF_8.displayName());
        return unPadding(s);
    }

    private static String padding(String data){
        StringBuilder sb = new StringBuilder(data);
        // length has to be multiple of 16
        int lengthFactor = 16;
        while(sb.length()% lengthFactor != 0){
            sb.append(PADDING_CHAR);
        }
        return sb.toString();
    }

    private static String unPadding(String data){
        StringBuilder sb = new StringBuilder(data);
        while(sb.length()>0 && sb.charAt(sb.length()-1) == PADDING_CHAR){
            sb.deleteCharAt(sb.length()-1);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        try {
            String encrypt = encrypt("123456");
            System.out.println(encrypt);
            System.out.println(decrypt(encrypt));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
